package com.wing.wcabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.PageResult;
import com.wing.product.model.response.ProductDetailVO;
import com.wing.product.service.ProductDetailService;
import com.wing.wcabinet.dao.WauthorityManageDao;
import com.wing.wcabinet.model.entity.WauthorityManage;
import com.wing.wcabinet.model.entity.WauthorityMateriel;
import com.wing.wcabinet.model.entity.WauthorityMember;
import com.wing.wcabinet.model.request.WauthorityManageForm;
import com.wing.wcabinet.model.response.WauthorityManageVO;
import com.wing.wcabinet.model.response.WauthorityMaterielVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 权限管理表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class WauthorityManageServiceImpl extends ServiceImpl<WauthorityManageDao, WauthorityManage> implements WauthorityManageService {


    @Autowired
    private WauthorityMaterielService authorityMaterielService;
    @Autowired
    private ProductDetailService productDetailService;
    @Autowired
    private WauthorityMemberService authorityMemberService;
    @Override
    public int add(WauthorityManageForm authorityManageForm) {
        //校验
        WauthorityManage authorityManage =new WauthorityManage();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(WauthorityManage.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(authorityManageForm, authorityManage, copyOptions);
        int a = baseMapper.insert(authorityManage);
        if (authorityManageForm.getAuthorityMaterielList()!=null){
            for(WauthorityMateriel authorityMateriel:authorityManageForm.getAuthorityMaterielList()){
                authorityMateriel.setManageId(authorityManage.getId());
            }
            if(!authorityMaterielService.saveBatch(authorityManageForm.getAuthorityMaterielList())){
                return  0;
            }
        }
        return a;
    }

    @Override
    public List<WauthorityManageVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<WauthorityManageVO> pageList4app(Page page, Map<String, Object> params) {
        List<WauthorityManageVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public WauthorityManageVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public int enable(Long id,String type) {
        WauthorityManageVO manageVO = baseMapper.get4appById(id);
        if(manageVO!=null && StringUtils.isNotBlank(type)){
            WauthorityManage authorityManage = new WauthorityManage();
            authorityManage.setId(manageVO.getId());
            if(type.equals("0")){
                authorityManage.setStatus(0l);
            }else if(type.equals("1")){
                authorityManage.setStatus(1l);
            }
            return baseMapper.updateById(authorityManage);
        }
        return 0;
    }

    @Transactional
    @Override
    public int updateAuthorityManage(WauthorityManageForm authorityManageForm) {
        WauthorityManage authorityManage = baseMapper.selectById(authorityManageForm.getId());
        if(authorityManage == null){
            throw new BusinessException("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(WauthorityManage.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(authorityManageForm, authorityManage, copyOptions);
        int result = baseMapper.updateById(authorityManage);

        //这个权限组已经有了的物料
        List<WauthorityMaterielVO> authorityMaterielVOList=authorityMaterielService.list4app(new HashMap(){{put("manageId",authorityManageForm.getAuthorityMaterielList().get(0).getManageId());}});


        if(authorityManageForm.getAuthorityMaterielList()!=null){
            List<Long> ids = new ArrayList<>();
            for (int i = 0; i < authorityManageForm.getAuthorityMaterielList().size(); i++) {
                if (authorityManageForm.getAuthorityMaterielList().get(i).getId()!=null){//修改已经有的
                    ids.add(authorityManageForm.getAuthorityMaterielList().get(i).getId());
                }else{//新添加的
                    WauthorityMateriel authorityMateriel = new WauthorityMateriel();
                    CopyOptions copyOptions1 = CopyOptions.create()
                            .setEditable(WauthorityMateriel.class)
                            .setIgnoreError(true)
                            .setIgnoreNullValue(true);
                    BeanUtil.copyProperties(authorityManageForm.getAuthorityMaterielList().get(i), authorityMateriel, copyOptions1);
                    authorityMateriel.setManageId(authorityManage.getId());
                    authorityMaterielService.save(authorityMateriel);
                }
            }
            for (WauthorityMaterielVO authorityMaterielVO:authorityMaterielVOList){
                if (!ids.contains(authorityMaterielVO.getId())){
                    //刪除沒有了的
                    authorityMaterielService.getBaseMapper().deleteById(authorityMaterielVO.getId());
                }
            }
        }else{
            return 0;
        }
        return result;
    }




    @Override
    public PageResult findMateriel(Integer page, Integer limit, String ids, Long authorityManageId, String categoryIds, String skuName, String skuCode, String oldSpecCode, String productBrandName) {
        //限制方式按分类添加
        if (categoryIds!=null&&authorityManageId==null){
            String [] a = categoryIds.split(",");
            List<ProductDetailVO> list = new ArrayList<>();
            for (int i = 0; i <a.length ; i++) {
                HashMap map = new HashMap();
                map.put("productCategoryId",Long.valueOf(a[i]));
                list.addAll(productDetailService.list4app(map));
            }
            if (ids!=null) {//添加时筛选掉已经选择的
                String [] b = ids.split(",");
                List<ProductDetailVO> list1 = new ArrayList<>();
                for (ProductDetailVO productDetailVO:list){
                    for (int i = 0; i <b.length ; i++) {
                        if(b[i]==productDetailVO.getSkuCode()){
                            list1.add(productDetailVO);
                        }
                    }
                }
                list.removeAll(list1);
            }
            /*List<ProductDetailVO> voList = new ArrayList<>();
            if (page==(list.size()/limit)+1){
                for (int i = (page-1)*limit; i < list.size(); i++) {
                    voList.add(list.get(i));
                }
            }else{
                for (int i = (page-1)*limit; i < limit*page; i++) {
                    voList.add(list.get(i));
                }
            }*/
            return new PageResult<>(list, list.size());
        }
        //限制方式按物料 添加
        if (categoryIds==null&&authorityManageId==null){
            HashMap map = new HashMap();
            if(skuName!=null){
                map.put("skuName",skuName);
            }
            if(skuCode!=null){
                map.put("skuCode",skuCode);
            }
            if(oldSpecCode!=null){
                map.put("oldSpecCode",oldSpecCode);
            }
            if(productBrandName!=null){
                map.put("productBrandName",productBrandName);
            }
            Page<ProductDetailVO> pg = new Page<>(page, limit);
            IPage<ProductDetailVO> list = productDetailService.pageList4app(pg,map);
            if (ids!=null) {//添加时筛选掉已经选择的
                List<ProductDetailVO> productDetailVOList = productDetailService.list4app(map);
                String [] b = ids.split(",");
                List<ProductDetailVO> list1 = new ArrayList<>();
                for (ProductDetailVO productDetailVO:productDetailVOList){
                    for (int i = 0; i <b.length ; i++) {
                        if(b[i].equals(productDetailVO.getSkuCode())){
                            list1.add(productDetailVO);
                        }
                    }
                }
                productDetailVOList.removeAll(list1);
                List<ProductDetailVO> voList = new ArrayList<>();
                if (page==(productDetailVOList.size()/limit)+1){
                    for (int i = (page-1)*limit; i < productDetailVOList.size(); i++) {
                        voList.add(productDetailVOList.get(i));
                    }
                }else{
                    for (int i = (page-1)*limit; i < limit*page; i++) {
                        voList.add(productDetailVOList.get(i));
                    }
                }
                return new PageResult<>(voList, productDetailVOList.size());
            }

            return new PageResult<>(list.getRecords(), list.getTotal());
        }


        //查看详情 修改
        if(authorityManageId!=null){
            WauthorityManageVO authorityManageVO = baseMapper.get4appById(authorityManageId);
            //根据分类 查询出所有物料
            //之前有的 物料限制阈值 为设置好的
            //没有的 为统一设置的值
            //限制方式按分类
            if (authorityManageVO.getRestrictWay().equals(WauthorityManage.RestrictWay.category)) {
                //根据分类 查询出所有物料
                //之前有的 物料限制阈值 为设置好的
                //没有的 为统一设置的值
                List<WauthorityMaterielVO> list = new ArrayList<>();
                String authorityManageCategoryIds = authorityManageVO.getMaterialId();
                String[] a = authorityManageCategoryIds.split(",");
                for (int i = 0; i < a.length; i++) {
                    HashMap map = new HashMap();
                    map.put("productCategoryId", Long.valueOf(a[i]));
                    List<ProductDetailVO> listProductDetail = productDetailService.list4app(map);//目前该分类下的物料
                    HashMap map1 = new HashMap();
                    map1.put("manageId", authorityManageId);
                    map1.put("categoryId", Long.valueOf(a[i]));
                    List<WauthorityMaterielVO> listAuthorityMateriel = authorityMaterielService.list4app(map1);//之前添加过的该分类的物料
                    List<ProductDetailVO> list1 = new ArrayList<>();
                    for (int j = 0; j < listProductDetail.size(); j++) {
                        for (int k = 0; k < listAuthorityMateriel.size(); k++) {
                            if (listProductDetail.get(j).getSkuCode().equals(listAuthorityMateriel.get(k).getSkuCode())) {
                                list1.add(listProductDetail.get(j));
                            }
                        }
                    }
                    listProductDetail.removeAll(list1);
                    for (ProductDetailVO productDetailVO:listProductDetail){
                        WauthorityMaterielVO authorityMaterielVO = new WauthorityMaterielVO();
                        authorityMaterielVO.setProductBrandName(productDetailVO.getBrandName());
                        authorityMaterielVO.setCategoryId(Long.valueOf(a[i]));
                        authorityMaterielVO.setManageId(authorityManageId);
                        authorityMaterielVO.setProductPic(productDetailVO.getProductPic());
                        authorityMaterielVO.setSkuCode(productDetailVO.getSkuCode());
                        authorityMaterielVO.setSkuName(productDetailVO.getSkuName());
                        authorityMaterielVO.setOldSpecCode(productDetailVO.getOldSpecCode());
                        authorityMaterielVO.setUnitName(productDetailVO.getUnitName());
                        listAuthorityMateriel.add(authorityMaterielVO);
                    }
                    list.addAll(listAuthorityMateriel);
                }
               /* List<AuthorityMaterielVO> voList = new ArrayList<>();
                if (page==(list.size()/limit)+1){
                    for (int i = (page-1)*limit; i < list.size(); i++) {
                        voList.add(list.get(i));
                    }
                }else{
                    for (int i = (page-1)*limit; i < limit*page; i++) {
                        voList.add(list.get(i));
                    }
                }*/
                return new PageResult<>(list, list.size());
            }else{
                //HashMap map = new HashMap();
                //限制方式按物料
                //map.put("manageId", authorityManageId);
                //Page<AuthorityMaterielVO> pg = new Page<>(page, limit);
                //IPage<AuthorityMaterielVO> list = authorityMaterielService.pageList4app(pg,map);
                List<WauthorityMaterielVO> list1 = new ArrayList<>();
                List<WauthorityMateriel> list = authorityMaterielService.list(new QueryWrapper<WauthorityMateriel>().eq("manage_id",authorityManageId));
                for (WauthorityMateriel wauthorityMateriel:list){
                    HashMap map = new HashMap();
                    map.put("skuCode",wauthorityMateriel.getSkuCode());
                    List<ProductDetailVO> listProductDetail = productDetailService.list4app(map);
                    for (ProductDetailVO productDetailVO:listProductDetail){
                        WauthorityMaterielVO authorityMaterielVO = new WauthorityMaterielVO();
                        authorityMaterielVO.setProductBrandName(productDetailVO.getBrandName());
                        authorityMaterielVO.setManageId(authorityManageId);
                        authorityMaterielVO.setProductPic(productDetailVO.getProductPic());
                        authorityMaterielVO.setSkuCode(productDetailVO.getSkuCode());
                        authorityMaterielVO.setSkuName(productDetailVO.getSkuName());
                        authorityMaterielVO.setOldSpecCode(productDetailVO.getOldSpecCode());
                        authorityMaterielVO.setUnitName(productDetailVO.getUnitName());
                        authorityMaterielVO.setId(wauthorityMateriel.getId());
                        list1.add(authorityMaterielVO);
                    }
                }

                return new PageResult<>(list1, list1.size());
            }
        }

        return null;

    }

    @Override
    public boolean removeAll(Long authorityManageId) {
        QueryWrapper<WauthorityMateriel> queryWrapper = new QueryWrapper<WauthorityMateriel>();
        queryWrapper.eq("manage_id",authorityManageId);
        QueryWrapper<WauthorityMember> wrapper = new QueryWrapper<WauthorityMember>();
        wrapper.eq("authority_manage_id",authorityManageId);
        if (baseMapper.deleteById(authorityManageId)>0&&authorityMaterielService.remove(queryWrapper)&&authorityMemberService.remove(wrapper)){
            return true;
        }
        return false;
    }

}
